package com.oristartech.netty.client.handler;

import com.oristartech.netty.client.config.NettyClientConfig;
import com.oristartech.netty.client.starter.NettyClientSender;
import com.oristartech.netty.common.message.MessageBuilder;
import com.oristartech.netty.common.message.MessageType;
import com.oristartech.netty.common.message.RegisterMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 ** Netty客户端注册通道处理
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-03-17 15:59
 * @blame Team
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyClientRegisterHandler extends ChannelInboundHandlerAdapter {

    /**
     ** Netty客户端发送
     */
    @Resource
    NettyClientSender nettyClientSender;

    /**
     ** 影院属性配置
     */
    @Resource
    NettyClientConfig nettyClientConfig;

    /**
     ** 通道激活时触发，发送信息给服务端进行注册
     *
     * @param ctx 通道上下文
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("客户端[{}-{}]连接成功", nettyClientConfig.getTenantId(), nettyClientConfig.getCinemaCode());
        // 发送注册信息给服务器，包含租户ID及影院编码
        RegisterMessage registerMessage = MessageBuilder.buildRegisterMessage(
                nettyClientConfig.getTenantId(), nettyClientConfig.getCinemaCode());
        ctx.writeAndFlush(registerMessage.toDataObject());
        ctx.fireChannelActive();
    }

    /**
     ** 读取数据处理，注册成功并缓存当前的客户端通道
     *
     * @param ctx 通道上下文
     * @param msg 读取到的数据
     * @throws Exception 处理过程中存在异常则抛出
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageBuilder messageBuilder = MessageBuilder.of(msg);
        if (messageBuilder.isMessage(MessageType.REGISTER)) {
            // 缓存客户端通道
            nettyClientSender.setChannel(ctx.channel());
            log.info("客户端[{}-{}]注册成功",
                    messageBuilder.getMessage().getTenantId(),
                    messageBuilder.getMessage().getCinemaCode());
            return;
        }
        ctx.fireChannelRead(msg);
    }

    /**
     ** 客户端失去连接处理，清空缓存的客户端通道
     *
     * @param ctx 通道上下文
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 清空缓存的客户端通道
        nettyClientSender.clear();
        ctx.fireChannelInactive();
    }
}
